package com.motorola.dp.jenkinsmonitor.service.util.dom;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.w3c.dom.Element;

import com.motorola.dp.jenkinsmonitor.model.util.dom.DomAttribute;
import com.motorola.dp.jenkinsmonitor.service.util.ClassService;

@Component("domAttributeProcessor")
public class DomAttributeProcessor implements DomAnnotationProcessor {

    @Value("#{classService}")
    private ClassService classService;

    @SuppressWarnings("rawtypes")
    public void processField(Field field, Element node, Object model) throws Exception {
        String attributeName = getAttributeName(field);

        if (!node.hasAttribute(attributeName)) {
            // attribute not specified
            return;
        }
        String attributeValue = node.getAttribute(attributeName);

        Class setterParameterClass = field.getType();
        Object setterParameter = classService.convertStringToClass(attributeValue, setterParameterClass);
        Method setterMethod = classService.getSetterMethod(field, model.getClass());

        setterMethod.invoke(model, setterParameter);
    }

    private String getAttributeName(Field field) {
        DomAttribute attribute = field.getAnnotation(DomAttribute.class);

        String attributeName = attribute.name();
        if (DomAttribute.NAME_UNSPECIFIED.equalsIgnoreCase(attributeName)) {
            attributeName = field.getName();
        }
        attributeName = attributeName.toLowerCase();

        return attributeName;
    }

    public void setClassService(ClassService classService) {
        this.classService = classService;
    }

}
